package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.Characteristic;
import com.wildlife.springboot.service.ICharacteristicService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/characteristic")
public class CharacteristicController {
    @Resource
    private ICharacteristicService characteristicService;

//    @PostMapping("/login")
//    public Result login(@RequestBody UserDTO userDTO){
//        String username = userDTO.getUsername();
//        String password = userDTO.getPassword();
//        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//        UserDTO dto = userService.login(userDTO);
//        return Result.success(dto);
//    }
//
//    @PostMapping("/register")
//    public Result register(@RequestBody UserDTO userDTO){
//        String username = userDTO.getUsername();
//        String password = userDTO.getPassword();
//        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//        return Result.success(userService.register(userDTO));
//    }

    //新增和修改
    @PostMapping
    public Result save(@RequestBody Characteristic characteristic){
        //新增或更新
        return Result.success(characteristicService.saveOrUpdate(characteristic));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(characteristicService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(characteristicService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(characteristicService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(characteristicService.getById(id));
    }

    @GetMapping("/head/{head}")
    public Result findOne(@PathVariable String head) {
        QueryWrapper<Characteristic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("head", head);
        return Result.success(characteristicService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize
//                           @RequestParam(defaultValue = "") String head
    ) {
        QueryWrapper<Characteristic> queryWrapper = new QueryWrapper<>();
//        if (id != null) {
//            queryWrapper.like("id", id);
//        }
//        if (!"".equals(head)) {
//            queryWrapper.like("head", head);
//        }
        return Result.success(characteristicService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Characteristic> list = characteristicService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("chineseName", "中文名");
        writer.addHeaderAlias("englishName", "英文名");
        writer.addHeaderAlias("scientificName", "学名");
        writer.addHeaderAlias("nickname", "别名");
        writer.addHeaderAlias("commonName", "俗名");
        writer.addHeaderAlias("kingdom", "界");
        writer.addHeaderAlias("phylum", "门");
        writer.addHeaderAlias("animalClass", "纲");
        writer.addHeaderAlias("subclass", "亚纲");
        writer.addHeaderAlias("animalOrder", "目");
        writer.addHeaderAlias("animalFamily", "科");
        writer.addHeaderAlias("genus", "属");
        writer.addHeaderAlias("identifyingFeature", "鉴别特征");
        writer.addHeaderAlias("appearance", "外形");
        writer.addHeaderAlias("furColor", "毛色");
        writer.addHeaderAlias("color", "颜色");
        writer.addHeaderAlias("limb", "四肢");
        writer.addHeaderAlias("skull", "头骨");
        writer.addHeaderAlias("teeth", "牙齿");
        writer.addHeaderAlias("weight", "体重");
        writer.addHeaderAlias("length", "体长");
        writer.addHeaderAlias("mouthPeak", "嘴峰");
        writer.addHeaderAlias("tarsometatarsalLength", "跗蹠长");
        writer.addHeaderAlias("tail", "尾长");
        writer.addHeaderAlias("wingLength", "翅长");
        writer.addHeaderAlias("fullLength", "全长");
        writer.addHeaderAlias("headLength", "头长");
        writer.addHeaderAlias("headBodyLength", "头体长");
        writer.addHeaderAlias("bodyHeight", "体高");
        writer.addHeaderAlias("bodyWidth", "体宽");
        writer.addHeaderAlias("hindFootLength", "后足长");
        writer.addHeaderAlias("earLength", "耳长");
        writer.addHeaderAlias("skullLength", "颅全长");
        writer.addHeaderAlias("skullBaseLength", "颅基长");
        writer.addHeaderAlias("palatalLength", "腭长");
        writer.addHeaderAlias("snoutLength", "吻长");
        writer.addHeaderAlias("intermolarWidth", "臼齿间宽");
        writer.addHeaderAlias("zygomaticWidth", "颧宽");
        writer.addHeaderAlias("orbitalWidth", "眶间宽");
        writer.addHeaderAlias("backHeadWidth", "后头宽");
        writer.addHeaderAlias("upperDentitionLength", "上齿列长");
        writer.addHeaderAlias("lowerDentitionLength", "下齿列长");
        writer.addHeaderAlias("abdominalScale", "腹鳞");
        writer.addHeaderAlias("buccalScale", "颊鳞");
        writer.addHeaderAlias("anteriorTemporalScale", "前颞鳞");
        writer.addHeaderAlias("posteriorTemporalScale", "后颞鳞");
        writer.addHeaderAlias("dorsalScale", "背鳞");
        writer.addHeaderAlias("caudalScale", "尾下鳞");
        writer.addHeaderAlias("snoutScale", "吻鳞");
        writer.addHeaderAlias("internasalScale", "鼻间鳞");
        writer.addHeaderAlias("supraocularScale", "眼上鳞");
        writer.addHeaderAlias("supraorbitalScale", "眶上鳞");
        writer.addHeaderAlias("nasalScale", "鼻鳞");
        writer.addHeaderAlias("prefossaScale", "窝前鳞");
        writer.addHeaderAlias("subfossaScale", "窝下鳞");
        writer.addHeaderAlias("upperLipScale", "上唇鳞");
        writer.addHeaderAlias("lowerLipScale", "下唇鳞");
        writer.addHeaderAlias("temporalScale", "颞区鳞");
        writer.addHeaderAlias("superiorCiliaryScale", "上睫鳞");
        writer.addHeaderAlias("caudalVentralScale", "尾腹鳞");
        writer.addHeaderAlias("dorsalArmorLength", "背甲长");
        writer.addHeaderAlias("dorsalArmorWidth", "背甲宽");
        writer.addHeaderAlias("dorsalArmorHeight", "背甲高");
        writer.addHeaderAlias("dorsalDiscLength", "背盘长");
        writer.addHeaderAlias("dorsalDiscWidth", "背盘宽");
        writer.addHeaderAlias("dorsalDiscHeight", "背盘高");
        writer.addHeaderAlias("prefrontalScale", "前额鳞");
        writer.addHeaderAlias("vertebralShield", "椎盾");
        writer.addHeaderAlias("costalShield", "肋盾");
        writer.addHeaderAlias("borderShield", "缘盾");
        writer.addHeaderAlias("shoulderHeight", "肩高");
        writer.addHeaderAlias("honking", "鸣声");
        writer.addHeaderAlias("habitat", "栖息地");
        writer.addHeaderAlias("diet", "食性");
        writer.addHeaderAlias("reproductivePeriod", "繁殖期");
        writer.addHeaderAlias("pregnancyPeriod", "妊娠期");
        writer.addHeaderAlias("lifetime", "寿命");
        writer.addHeaderAlias("ovulationPeriod", "产卵期");
        writer.addHeaderAlias("eggCount", "窝卵数");
        writer.addHeaderAlias("eggWeight", "卵重");
        writer.addHeaderAlias("eggDiameter", "卵径");
        writer.addHeaderAlias("incubationPeriod", "孵化期");
        writer.addHeaderAlias("incubationRate", "孵化率");
        writer.addHeaderAlias("nest", "巢穴");
        writer.addHeaderAlias("nestDiameter", "巢径");
        writer.addHeaderAlias("nestSpacing", "巢间距");
        writer.addHeaderAlias("sexualMaturityTime", "性成熟时间");
        writer.addHeaderAlias("hibernant", "冬眠期");
        writer.addHeaderAlias("migrationTime", "迁徙时间");
        writer.addHeaderAlias("activity", "活动");
        writer.addHeaderAlias("naturalEnemy", "天敌");
        writer.addHeaderAlias("reproduction", "繁殖");
        writer.addHeaderAlias("populationSize", "种群数量");
        writer.addHeaderAlias("populationTrend", "种群趋势");
        writer.addHeaderAlias("biotope", "生境");
        writer.addHeaderAlias("ecosystem", "生态系统");
        writer.addHeaderAlias("domesticDistribution", "国内分布");
        writer.addHeaderAlias("foreignDistribution", "国外分布");
        writer.addHeaderAlias("endemicSpecie", "是否特有种");
        writer.addHeaderAlias("subspeciesDifferentiation", "亚种分化");
        writer.addHeaderAlias("protectedLevel", "国家重点保护野生动物等级");
        writer.addHeaderAlias("iucn", "IUCN红色名录");
        writer.addHeaderAlias("source", "来源");
        writer.addHeaderAlias("categoryCharacteristic", "种类特征");
        writer.addHeaderAlias("feature", "形态特征");
        writer.addHeaderAlias("distributionArea", "分布区域");
        writer.addHeaderAlias("mainComponents", "主要成分");
        writer.addHeaderAlias("effect", "功效");
        writer.addHeaderAlias("classification", "分类");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("动物特征", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("头部", "head");
        reader.addHeaderAlias("躯体", "body");
        reader.addHeaderAlias("尾部", "tail");
        reader.addHeaderAlias("颜色", "color");
        reader.addHeaderAlias("羽毛", "fur");
        reader.addHeaderAlias("四肢", "spoor");
        reader.addHeaderAlias("粪便", "feces");
        reader.addHeaderAlias("鸣声", "sound");
        List<Characteristic> list = reader.readAll(Characteristic.class);
        characteristicService.saveBatch(list);
        return true;
    }
}
